package com.wholeintech.zigbee.util;

import android.content.Context;
import android.content.Intent;
import android.net.LocalSocket;
import android.net.LocalSocketAddress;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;

import com.wholeintech.entity.BoxInfo;
import com.wholeintech.dao.BoxInfoDao;
import com.wholeintech.entity.DeviceDb;
import com.wholeintech.utils.CommonIntent;
import com.wholeintech.utils.CommonUtil;
import com.wholeintech.utils.CrashExceptionUtils;
import com.wholeintech.utils.LogUtils;
import com.wholeintech.zigbee.gw.DeviceControl;
import com.wholeintech.zigbee.gw.DeviceManager;
import com.wholeintech.zigbee.gw.ZigBeeDataProcess;
import com.wholeintech.zigbee.gw.ZigBeeService;

import org.xutils.DbManager;
import org.xutils.ex.DbException;

import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.LinkedBlockingQueue;
import java.lang.Integer;

import static com.wholeintech.utils.CommonIntent.ACTION_DEV_DEVCHANAGE;
import static com.wholeintech.utils.CommonUtil.bytesToHexString;
import static com.wholeintech.utils.CommonUtil.sendBroadcastMsg;

/**
 * Created by Lyle on 2016-01-18.
 */

public class SerialDataUnpack {

    private String TAG = "SerialDataUnpack";
    private static final boolean rxDebug = false;

    private static byte[] mUartInputBuffer = new byte[4096];
    private static byte[] mDeviceData = new byte[4096];
    private byte[] txDataByte;

    private HandlerThread mHandlerThreadRx = new HandlerThread("rxThread");
    private HandlerThread mHandlerThreadTx = new HandlerThread("txThread");
    private Handler mHandlerRX;
    private Handler mHandlerTX;
    private boolean isRunRXBufThread = false;
    private Handler dataProcessHandle;

    private static SerialDataUnpack mSerialDataUnpack;

    private LocalSocket mUartServer;
    private LocalSocketAddress address;
    private InputStream mUartIn;
    private OutputStream mUartOut;
    private static final String UART_SOCKET_NAME = "zb_uart_server";//"zb_uart_server";//"uart_server";//"zb_uart_server";

    private static final int mUartIn_PACKAGE_COUNT = 6;
    private static final byte PREAMBLE = (byte) 0xFC;//preamble
    private static final byte PREAMBLE_LEN = 1;//preamble len
    private static final byte FIX_LEN_BYTES = 5;//preamble+len+pt+cmd+crc
    private static final byte LEN_DATA_BYTE_COUNT = 1;
    private static final byte PACKETTYPE_CMD_BYTES_COUNT = 2;
    private static final byte XOR_BYTE_COUNT = 1;
    private static final int MAX_RX_DATA_BYTES = 50;//0xff ;//数据段的最大长度

    private static final int MAX_WatchDog = 50 * 10;//0xff ;//数据段的最大长度

    private boolean oneGroupCompleteFlag = true;
    private Context mContext;

    LinkedBlockingQueue<String> txSendDataQueue = new LinkedBlockingQueue<>();
    public LinkedBlockingQueue<Intent> intentQueue = new LinkedBlockingQueue<>();

    public boolean needCheckTimeOut = false;

    private SerialDataUnpack(Context context) {
        mContext = context;
    }

    public static SerialDataUnpack getSingleInstance(Context context) {
        if (mSerialDataUnpack == null) {
            mSerialDataUnpack = new SerialDataUnpack(context);
        }
        return mSerialDataUnpack;
    }

    public boolean initSerial() {
        mHandlerThreadRx.start();
        mHandlerThreadTx.start();

        mHandlerRX = new Handler(mHandlerThreadRx.getLooper());
        mHandlerTX = new Handler(mHandlerThreadTx.getLooper());

        mUartServer = new LocalSocket();
        address = new LocalSocketAddress(UART_SOCKET_NAME, LocalSocketAddress.Namespace.RESERVED);
        try {

            if (!mUartServer.isConnected()) {
                mUartServer.connect(address);
                if (rxDebug) Log.d(TAG, "Connect socket server!");
            }

            mUartIn = mUartServer.getInputStream();
            mUartOut = mUartServer.getOutputStream();

            byte buf[] = {'C', 'o', 'n', '_', 'U', 'T'};
            byte rxBuf[] = new byte[1024];

            try {
                mUartOut.write(buf, 0, buf.length);
                int count = mUartIn.read(rxBuf);
                byte reccmdbuf[] = new byte[count];
                for (int i = 0; i < count; i++)
                    reccmdbuf[i] = rxBuf[i];

                if (count > 0) {
                    String revData = new String(reccmdbuf, "UTF-8");

                    if (revData.equals("sucess"))
                        return true;
                    else
                        return false;
                }
            } catch (Exception e) {
                Log.e(TAG, "Socket write data fail!");
            }
        } catch (Exception e) {
            Log.e(TAG, "Connect uart server fail!");
        }

        return false;
    }

    public boolean startRx(Handler mHandler) {
        if (mUartServer != null) {
            dataProcessHandle = mHandler;
            isRunRXBufThread = true;
            mHandlerRX.post(uartRxDataRunnable);
            new Thread(uartTxIntentRunnable).start();
            new Thread(uartTxDataRunnable).start();

            if (rxDebug) Log.d(TAG, "Start receive data!");

            return true;
        } else {
            Log.e(TAG, "No connect device!!!");
            return false;
        }
    }

    public void stopRx() {
        if (mUartServer != null && uartRxDataRunnable != null) {

            isRunRXBufThread = false;
            mHandlerRX.removeCallbacks(uartRxDataRunnable);

            if (mHandlerThreadRx.quitSafely()) {
                if (rxDebug)
                    Log.d(TAG, "Stop receive data!");
            }

            try {
                if (mUartServer.isConnected()) {
                    mUartServer.close();
                    Log.d(TAG, "Disconnect socket server!");
                }
            } catch (Exception e) {
                Log.d(TAG, "Close uart server fail!");
            }
        }
    }

    public void ReleaseObj() {
        mSerialDataUnpack = null;
    }

    /**
     *  发送控制指令线程
     *  此线程从队列里取出控制指令转发
     */
    Runnable uartTxDataRunnable = new Runnable() {
        @Override
        public void run() {
            String Txqueue;
            try {
                while ((Txqueue = txSendDataQueue.take()) != null) {
                    txDataByte = CommonUtil.hex2byte(Txqueue);
                    if (mUartOut != null) {
                        //发送控制指令到控制模块
                        mUartOut.write(txDataByte);
                        needCheckTimeOut = true;
                        Log.e("ACTION_CTL_LIGHT_8","====ACTION_CTL_LIGHT_8===uartTxDataRunnable====mUartOut.write:==Txqueue："+Txqueue);
                    }

                    LogUtils.d(TAG, "write data str:" + CommonUtil.bytesToHexString(txDataByte, txDataByte.length));
                    Thread.sleep(110);
                }
            } catch (Exception e) {
                Log.e(TAG, "write  data IOException" + " RestartService" + e);
                CrashExceptionUtils.getInstance().forceRestart(mContext);
            }
        }
    };
    Runnable uartTxIntentRunnable = new Runnable() {
        @Override
        public void run() {
            Intent txIntent;
            if (mUartOut != null) {
                try {
                    while ((txIntent = intentQueue.take()) != null) {
                        intentControlCmdProc(txIntent);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    };

    /**
     * 清空指令队列
     */
    public void cleanBuff() {
        txSendDataQueue.clear();
        Log.e(TAG, "SerialDataUnpack clearBuff!!!");
    }

    /**
     * 控制指令加入队列
     * @param code
     */
    public synchronized void writeCmd(byte[] code) {
        if (txSendDataQueue != null) {
            try {
                txSendDataQueue.put(CommonUtil.bytesToHexString(code, code.length));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    private int uart_Rx_tick = 0;

    Runnable uartRxDataRunnable = new Runnable() {
        //Unpack Rx data for ZigBee
        @Override
        public void run() {
            if (rxDebug) Log.d(TAG, "Serial Receive Runnable Run...");

            int RxLenByteInt = 0;
            int i, j, lenDataOffset, lenPackDataInt;

            while (isRunRXBufThread) {
                try {
                    if (mUartIn == null) {
                        Log.e(TAG, "RXBufThread mSerialPort == null,Thread exit");
                        return;
                    }
                    uart_Rx_tick++;
                    if (uart_Rx_tick > 1000) {
                        Log.d(TAG, "uart_Rx_tick run !!");
                        uart_Rx_tick = 0;
                    }

                    int len = mUartIn.available();
                    if (len <= 0) {
                        Thread.sleep(30);
                        continue;
                    }
                    int ret = mUartIn.read(mUartInputBuffer);

                    if (ret <= 0) {
                        Thread.sleep(30);
                        continue;
                    }
                    for (i = 0; i < ret; i++) {
                        mDeviceData[RxLenByteInt++] = mUartInputBuffer[i];
                    }
                    if (rxDebug) {
                        Log.d(TAG, "Rx Data:" + bytesToHexString(mDeviceData, RxLenByteInt) + ",len:" + RxLenByteInt);
                    }

                    if (RxLenByteInt < mUartIn_PACKAGE_COUNT) {
                        Thread.sleep(30);
                        continue;
                    }

                    if ((PREAMBLE == mDeviceData[0]) || (!oneGroupCompleteFlag)) {//HEAD
                        lenDataOffset = PREAMBLE_LEN;
                        lenPackDataInt = mDeviceData[PREAMBLE_LEN] & 0xff;//pack data length
                        if (lenPackDataInt < MAX_RX_DATA_BYTES) {

                            for (i = 0; (i + lenPackDataInt + FIX_LEN_BYTES) <= RxLenByteInt; ) { //FIX_LENGHT_BYTES=preamble+len+crc, Have receive complete pack

                                if (rxDebug) {
                                    Log.d(TAG, "pack:" + bytesToHexString(mDeviceData, RxLenByteInt));
                                }

                                if (PREAMBLE == mDeviceData[lenDataOffset - PREAMBLE_LEN]) {
                                    byte[] newUnpackData = new byte[lenPackDataInt + PACKETTYPE_CMD_BYTES_COUNT];
                                    for (j = 0; j < lenPackDataInt + PACKETTYPE_CMD_BYTES_COUNT; j++)
                                        newUnpackData[j] = mDeviceData[lenDataOffset + j + LEN_DATA_BYTE_COUNT];//unpack data

                                    Log.d(TAG, "Unpack:" + bytesToHexString(newUnpackData, newUnpackData.length));

                                    Message mNewUnpackMsg = new Message();
                                    mNewUnpackMsg.what = ZigBeeDataProcess.UNPACK_RX_DATA;
                                    mNewUnpackMsg.obj = newUnpackData;
                                    dataProcessHandle.sendMessage(mNewUnpackMsg);

                                    i += lenPackDataInt + FIX_LEN_BYTES;//complete rx packet len
                                    lenDataOffset = i + PREAMBLE_LEN;

                                    if (lenDataOffset <= RxLenByteInt)
                                        lenPackDataInt = mDeviceData[lenDataOffset] & 0xff;//pack data length
                                    else
                                        lenPackDataInt = i;

                                } else {
                                    Log.e(TAG, "Receive not complete pack,clean!");
                                    RxLenByteInt = 0;
                                    break;
                                }
                            }
                            if (rxDebug)
                                Log.d(TAG, "RxLenByteInt=" + RxLenByteInt + ",i=" + i);

                            if (RxLenByteInt != 0) {
                                if ((RxLenByteInt = RxLenByteInt - i) == 0) {
                                    oneGroupCompleteFlag = true;
                                } else {
                                    for (j = 0; j < RxLenByteInt; j++)  //Not receive complete pack
                                        mDeviceData[j] = mDeviceData[j + i];

                                    oneGroupCompleteFlag = false;
                                }
                            } else {
                                oneGroupCompleteFlag = true;
                            }

                            if (rxDebug)
                                Log.d(TAG, "RxLenByteInt=" + RxLenByteInt + ",CompleteFlag=" + oneGroupCompleteFlag + "," + bytesToHexString(mDeviceData, RxLenByteInt));

                        } else {
                            RxLenByteInt = 0;
                            oneGroupCompleteFlag = true;
                            Log.e(TAG, "Rx data len Error:" + lenPackDataInt);
                        }
                    } else {
                        RxLenByteInt = 0;
                    }
//                    Thread.sleep(20);//20ms读取一次缓冲的数据
                } catch (Exception e) {
                    Log.e(TAG, "SerialRX Error:" + e);
                }
            }
        }
    };

    /**
     * 处理上层下发的控制Intent
     * @param intent
     */
    public void intentControlCmdProc(Intent intent) {
        com.wholeintech.utils.LogUtils.d(TAG,"====intentControlCmdProc==intent:"+intent.toUri(0));
        String mac = intent.getStringExtra("macAddr");
        String deviceId = intent.getStringExtra("deviceId");
        DeviceDb me;
        DeviceDb gwDev;

        DbManager db = CommonUtil.MyDbUtils();
        int refresh = 1;

        try {
            if (intent.getAction().equals(CommonIntent.ACTION_CTL_CLEAR_BUFFER)) {
                cleanBuff();
                return;
            }

            me = db.selector(DeviceDb.class).where("devId", "=", deviceId).findFirst();
            if (me == null) {
                Log.d(TAG, "Not found, devId:" + deviceId);
                return;
            }

            gwDev = db.selector(DeviceDb.class).where("devId", "=", me.getGwDevId()).findFirst();
            if (gwDev == null)
            {
                Log.d(TAG, "this dev has no gwDev" + gwDev);
            }

            int netType = intent.getIntExtra("network", me.getNetType());
            if ((me.getNetType() == DeviceManager.ETHERNET_NETWORK)
                    ||(!TextUtils.isEmpty(me.getGwDevId()) && (me.getDevId().length()!= DeviceManager.DEVICE_ZIGBEE_LIGHT8_SUB_DEVID_LEN/*whether is the sub device of ip2zigbee*/
                    || ((gwDev!=null) && (gwDev.getType() == DeviceManager.TYPE_LIGHT_8) && (gwDev.getGwDevId().length()>= DeviceManager.DEVICE_ZIGBEE_DEVID_LEN))))/*whether is the light_8 sub device of ip2zigbee*/
                    || (netType == DeviceManager.KNX_NETWORK)) {
                Log.d(TAG, "!!!!!!ZigBee Service To ACTION_DEV_CTL_BY_WIRED_NET!!!!!!");
                intent.putExtra("currentAction", intent.getAction());
                intent.setAction(CommonIntent.ACTION_DEV_CTL_BY_WIRED_NET);
                mContext.sendBroadcast(intent);
                return;
            } else if (netType != DeviceManager.ZIGBEE_NETWORK) {
                //Log.d(TAG, "This not Zigbee dev:" + deviceId);
                //转发给有线网
                if (netType == DeviceManager.BLE_NETWORK) {
                    Log.d(TAG, "!!!!!!ZigBee Service To ACTION_DEV_CTL_BY_BLE!!!!!!");
                    intent.putExtra("currentAction", intent.getAction());
                    intent.setAction(CommonIntent.ACTION_DEV_CTL_BY_BLE);
                    mContext.sendBroadcast(intent);
                }
                return;
            } else if (me.getGwDevId() != null) {
                if (me.getGwDevId().length() == 12
                        &&  (me.getDevId().length()!= DeviceManager.DEVICE_ZIGBEE_LIGHT8_SUB_DEVID_LEN)) {
                    Log.d(TAG, "This subDevice:" + me.getGwDevId());
                    return;
                }
            }

            BoxInfoDao boxinfoDao = new BoxInfoDao(mContext);
            List<BoxInfo> boxInfo = boxinfoDao.getBoxInfoList();

            if (boxInfo.get(0).getRegionId() != me.getRegionId()) {
                Log.d(TAG, "other region DEV CTL Name:" + me.getName());
                return;
            }

            Log.d(TAG, "ZigBee Service ACTION_DEV_CTL");

            Log.i(TAG, "CTL Name:" + me.getName());
            ArrayList<String> subDevList = new ArrayList<>();

            switch (intent.getAction()) {
                case CommonIntent.ACTION_CTL_LIGHT: {
                    //普通灯控制
                    int sw = intent.getIntExtra("sw", -1);
                    int brightness = intent.getIntExtra("brightness", 255);
                    int color = 0;
                    int channel;
                    int iDevid;

                    if (deviceId.length() > 12)
                    {
                        iDevid = Integer.parseInt(deviceId.substring(13, 16), 10);
                        channel = iDevid%10;
                        if (channel>=8 || sw > 1)
                        {
                            LogUtils.d(TAG, "light8 channel error:" + channel + "  iDevid:" + iDevid + " sw:" + sw);
                            return ;
                        }
                        color = channel;
                    }

                    if (sw == 0)
                        brightness = 0;
                    if (me.getSw() == sw && me.getBrightness() == brightness && me.getColor() == color) {
                        me.setSw(sw);
                        me.setBrightness(brightness);
                        me.setColor(color);
                        LogUtils.d(TAG, "Not Change MAC:" + mac + "devid:" + deviceId + ",sw:" + sw + ",brightness:" + brightness + ",color:" + color);
                    } else {
                        me.setSw(sw);
                        me.setBrightness(brightness);
                        me.setColor(color);
                        DeviceManager.flagLight8Devid=deviceId;
                        //发送状态改变广播
                        sendBroadcastMsg(mContext,ACTION_DEV_DEVCHANAGE,me.getBoxId(),me.getDevId(),me.getType(),false,null);
                        Log.e(TAG,"sendBroadcastMsg===10");
                        LogUtils.d(TAG, "**************Change MAC:" + mac + "devid:" + deviceId + ",sw:" + sw + ",brightness:" + brightness + ",color:" + color);
                    }

                    break;
                }
                case CommonIntent.ACTION_CTL_LIGHT_8:{
                    //Log.e(TAG,"============ACTION_CTL_LIGHT_8======");
                    //一拖八灯控制
                    int sw1 = intent.getIntExtra("sw1", -1);
                    int sw2 = intent.getIntExtra("sw2", -1);
                    int sw3 = intent.getIntExtra("sw3", -1);
                    int sw4 = intent.getIntExtra("sw4", -1);
                    int sw5 = intent.getIntExtra("sw5", -1);
                    int sw6 = intent.getIntExtra("sw6", -1);
                    int sw7 = intent.getIntExtra("sw7", -1);
                    int sw8 = intent.getIntExtra("sw8", -1);
                    int temp = 0;
                    int channel = 0;
                    DeviceDb subDevDb;
                    StringBuilder subDeviceId = new StringBuilder();
                    subDeviceId.append("1030");
                    subDeviceId.append(deviceId.substring(4,12));
                    subDeviceId.append("0000");

                    if (sw1 >= 0)
                    {
                        temp += (sw1*(1<<0));
                        channel += (1<<0);
                        subDevDb = db.selector(DeviceDb.class).where("devId", "=", subDeviceId.toString()).findFirst();
                        if(subDevDb!= null && sw1 != subDevDb.getSw()) {
                            subDevDb.setSw(sw1);
                            db.saveOrUpdate(subDevDb);
                            subDevList.add(subDeviceId.toString());
                            Log.d(TAG, "==ACTION_CTL_LIGHT_8==devid:" + subDeviceId.toString() + " sw:" + sw1);
                        }

                        //发送状态改变广播
                        sendBroadcastMsg(mContext,ACTION_DEV_DEVCHANAGE,subDevDb.getBoxId(),subDevDb.getDevId(),subDevDb.getType(),false,null);
                        Log.e(TAG,"sendBroadcastMsg===11");
                    }
                    if (sw2 >= 0)
                    {
                        temp += (sw2*(1<<1));
                        channel += (1<<1);
                        subDeviceId.setCharAt(15, '1');
                        subDevDb = db.selector(DeviceDb.class).where("devId", "=", subDeviceId.toString()).findFirst();
                        if(subDevDb!= null && sw2 != subDevDb.getSw())
                        {
                            subDevDb.setSw(sw2);
                            db.saveOrUpdate(subDevDb);
                            subDevList.add(subDeviceId.toString());
                            Log.d(TAG, "==ACTION_CTL_LIGHT_8==devid:" + subDeviceId.toString() + " sw:" + sw2);
                        }

                        //发送状态改变广播
                        sendBroadcastMsg(mContext,ACTION_DEV_DEVCHANAGE,subDevDb.getBoxId(),subDevDb.getDevId(),subDevDb.getType(),false,null);
                        Log.e(TAG,"sendBroadcastMsg===12");
                    }

                    if (sw3 >= 0) {
                        temp += (sw3*(1<<2));
                        channel += (1<<2);
                        subDeviceId.deleteCharAt(15);
                        subDeviceId.replace(15,15,"2");
                        subDevDb = db.selector(DeviceDb.class).where("devId", "=", subDeviceId.toString()).findFirst();
                        if(subDevDb!= null && sw3 != subDevDb.getSw()) {
                            subDevDb.setSw(sw3);
                            db.saveOrUpdate(subDevDb);
                            subDevList.add(subDeviceId.toString());
                            Log.d(TAG, "==ACTION_CTL_LIGHT_8==devid:" + subDeviceId.toString() + " sw:" + sw3);
                        }

                        //发送状态改变广播
                        sendBroadcastMsg(mContext,ACTION_DEV_DEVCHANAGE,subDevDb.getBoxId(),subDevDb.getDevId(),subDevDb.getType(),false,null);
                        Log.e(TAG,"sendBroadcastMsg===13");
                    }
                    if (sw4 >= 0) {
                        temp += (sw4*(1<<3));
                        channel += (1<<3);
                        subDeviceId.deleteCharAt(15);
                        subDeviceId.replace(15,15,"3");
                        subDevDb = db.selector(DeviceDb.class).where("devId", "=", subDeviceId.toString()).findFirst();
                        if(subDevDb!= null && sw4 != subDevDb.getSw()) {
                            subDevDb.setSw(sw4);
                            db.saveOrUpdate(subDevDb);
                            subDevList.add(subDeviceId.toString());
                            Log.d(TAG, "==ACTION_CTL_LIGHT_8==devid:" + subDeviceId.toString() + " sw:" + sw4);
                        }

                        //发送状态改变广播
                        sendBroadcastMsg(mContext,ACTION_DEV_DEVCHANAGE,subDevDb.getBoxId(),subDevDb.getDevId(),subDevDb.getType(),false,null);
                        Log.e(TAG,"sendBroadcastMsg===14");
                    }
                    if (sw5 >= 0) {
                        temp += (sw5*(1<<4));
                        channel += (1<<4);
                        subDeviceId.deleteCharAt(15);
                        subDeviceId.replace(15,15,"4");
                        subDevDb = db.selector(DeviceDb.class).where("devId", "=", subDeviceId.toString()).findFirst();
                        if(subDevDb!= null && sw5 != subDevDb.getSw()) {
                            subDevDb.setSw(sw5);
                            db.saveOrUpdate(subDevDb);
                            subDevList.add(subDeviceId.toString());
                            Log.d(TAG, "==ACTION_CTL_LIGHT_8==devid:" + subDeviceId.toString() + " sw:" + sw5);
                        }

                        //发送状态改变广播
                        sendBroadcastMsg(mContext,ACTION_DEV_DEVCHANAGE,subDevDb.getBoxId(),subDevDb.getDevId(),subDevDb.getType(),false,null);
                        Log.e(TAG,"sendBroadcastMsg===15");
                    }
                    if (sw6 >= 0) {
                        temp += (sw6*(1<<5));
                        channel += (1<<5);
                        subDeviceId.deleteCharAt(15);
                        subDeviceId.replace(15,15,"5");
                        subDevDb = db.selector(DeviceDb.class).where("devId", "=", subDeviceId.toString()).findFirst();
                        if(subDevDb!= null && sw6 != subDevDb.getSw()) {
                            subDevDb.setSw(sw6);
                            db.saveOrUpdate(subDevDb);
                            subDevList.add(subDevDb.getDevId());
                            Log.d(TAG, "==ACTION_CTL_LIGHT_8==devid:" + subDeviceId.toString() + " sw:" + sw6);
                        }

                        //发送状态改变广播
                        sendBroadcastMsg(mContext,ACTION_DEV_DEVCHANAGE,subDevDb.getBoxId(),subDevDb.getDevId(),subDevDb.getType(),false,null);
                        Log.e(TAG,"sendBroadcastMsg===16");
                    }
                    if (sw7 >= 0) {
                        temp += (sw7*(1<<6));
                        channel += (1<<6);
                        subDeviceId.deleteCharAt(15);
                        subDeviceId.replace(15,15,"6");
                        subDevDb = db.selector(DeviceDb.class).where("devId", "=", subDeviceId.toString()).findFirst();
                        if(subDevDb!= null && sw7 != subDevDb.getSw()) {
                            subDevDb.setSw(sw7);
                            db.saveOrUpdate(subDevDb);
                            subDevList.add(subDeviceId.toString());
                            Log.d(TAG, "==ACTION_CTL_LIGHT_8==devid:" + subDeviceId.toString() + " sw:" + sw7);
                        }

                        //发送状态改变广播
                        sendBroadcastMsg(mContext,ACTION_DEV_DEVCHANAGE,subDevDb.getBoxId(),subDevDb.getDevId(),subDevDb.getType(),false,null);
                        Log.e(TAG,"sendBroadcastMsg===17");
                    }
                    if (sw8 >= 0) {
                        temp += (sw8*(1<<7));
                        channel += (1<<7);
                        subDeviceId.deleteCharAt(15);
                        subDeviceId.replace(15,15,"7");
                        subDevDb = db.selector(DeviceDb.class).where("devId", "=", subDeviceId.toString()).findFirst();
                        if(subDevDb!= null && sw8 != subDevDb.getSw()) {
                            subDevDb.setSw(sw8);
                            db.saveOrUpdate(subDevDb);
                            subDevList.add(subDeviceId.toString());
                            Log.d(TAG, "==ACTION_CTL_LIGHT_8==devid:" + subDeviceId.toString() + " sw:" + sw8);
                        }

                        //发送状态改变广播
                        sendBroadcastMsg(mContext,ACTION_DEV_DEVCHANAGE,subDevDb.getBoxId(),subDevDb.getDevId(),subDevDb.getType(),false,null);
                        Log.e(TAG,"sendBroadcastMsg===18");
                    }
                    if (channel > 0) {
                        channel += (1<<15);//set 1to8 scene flag to mcu
                    }
                    me.setSw(temp);
                    me.setColor(channel);
                    Log.e("ACTION_CTL_LIGHT_8","====ACTION_CTL_LIGHT_8===控制一拖8灯===开始");
                    Log.e(TAG,"========ACTION_CTL_LIGHT_8======");
                    Log.d(TAG, "==ACTION_CTL_LIGHT_8==devid:" + deviceId + "temp:" + temp + "channel" + channel);
                }
                break;
                case CommonIntent.ACTION_CTL_AIRCONDITION:
                case CommonIntent.ACTION_CTL_FLOOR_HEATING: {
                    //空调地暖
                    //if (debug) Log.d(TAG, "ACTION_CTL_AIRCONDITION or ACTION_CTL_FLOOR_HEATING ");
                    int sw = intent.getIntExtra("sw", me.getSw());
                    int mode = intent.getIntExtra("mode", me.getMode());
                    int temp = intent.getIntExtra("temperature", me.getSetTemp());
                    int wind = intent.getIntExtra("wind", me.getWind());

                    if (me.getSw() == sw && me.getMode() == mode && me.getSetTemp() == temp && me.getWind() == wind) {
                        me.setSw(sw);
                        me.setMode(mode);
                        me.setSetTemp(temp);
                        me.setWind(wind);
                        LogUtils.i(TAG, "Not Change MAC:" + mac + "devid:" + deviceId + "sw" + sw + "temp:" + temp + ",wind:" + wind + ",mode:" + mode);
                    } else {
                        me.setSw(sw);
                        me.setMode(mode);
                        me.setSetTemp(temp);
                        me.setWind(wind);
                        LogUtils.i(TAG, "Change MAC:" + mac + "devid:" + deviceId + "sw" + sw + "temp:" + temp + ",wind:" + wind + ",mode:" + mode);
                    }
                    break;
                }
                case CommonIntent.ACTION_CTL_CURTAIN:
                    //窗帘
                    int runstate = intent.getIntExtra("runstate", -1);
                    int runstate2 = intent.getIntExtra("runstate2", -1);
                    int channel = intent.getIntExtra("channel", 0);

                    if(runstate !=-1){
                        me.setCurtainState(runstate);
                    }

                    if(runstate2 !=-1){
                        me.setCurtainState2(runstate2);
                    }
                    //不用通过通道来控制
//                    if (channel == 0) {
//                        if (me.getCurtainState() == runstate)
//                            refresh = 0;
//                        me.setCurtainState(runstate);
//                    } else {
//                        if (me.getCurtainState2() == runstate)
//                            refresh = 0;
//                        me.setCurtainState2(runstate);
//                    }
                    if (refresh == 1) {
                        LogUtils.i(TAG, "Change MAC:" + mac + "devid:" + deviceId + "channel" + channel + "runstate:" + runstate);
                    } else {

                        LogUtils.i(TAG, "Not Change MAC:" + mac + "devid:" + deviceId + "channel" + channel + "runstate:" + runstate);
                    }
                    break;
                case CommonIntent.ACTION_CTL_FRESHAIR: {
                    //新风
                    Log.e(TAG,"====ACTION_CTL_FRESHAIR===");
                    int sw = intent.getIntExtra("sw", me.getSw());
                    int wind = intent.getIntExtra("wind", me.getWind());
                    int mode = intent.getIntExtra("mode", me.getMode());
                    int sw2 = intent.getIntExtra("sw2", me.getCurtainState());
                    if (me.getSw() == sw && me.getWind() == wind && me.getMode() == mode && sw2 == me.getCurtainState()) {
                        me.setSw(sw);
                        me.setWind(wind);
                        me.setMode(mode);
                        me.setCurtainState(sw2);
                        LogUtils.i(TAG, "Not Change MAC:" + mac + "devid:" + deviceId + "sw" + sw + ",wind:" + wind + ",mode:" + mode + "ext" + sw2);
                    } else {
                        me.setSw(sw);
                        me.setWind(wind);
                        me.setMode(mode);
                        me.setCurtainState(sw2);
                        LogUtils.i(TAG, "Change MAC:" + mac + "devid:" + deviceId + "sw" + sw + ",wind:" + wind + ",mode:" + mode + "ext" + sw2);
                    }
                    break;
                }
                case CommonIntent.ACTION_CTL_SWITCH:
                    break;
            }

            me.setFbFlag(ZigBeeService.DEV_CTRL_UPDATA_FLAG);
            me.setRetryCnt(0);
            db.saveOrUpdate(me);
            DeviceControl.control(me);

            boolean isCtlLight8 = intent.getAction().equals(CommonIntent.ACTION_CTL_LIGHT_8);
            if(isCtlLight8) {
                CommonUtil.sendBroadcastMsg(mContext, ACTION_DEV_DEVCHANAGE, me.getBoxId(), me.getDevId(), me.getType(), true, subDevList);
                Log.e(TAG,"sendBroadcastMsg===19");
            }else{
                CommonUtil.sendBroadcastMsg(mContext, ACTION_DEV_DEVCHANAGE, me.getBoxId(), me.getDevId(), me.getType(), false, null);
                Log.e(TAG,"sendBroadcastMsg===20");
            }

            //其他设备类型，按照原来的处理运行
            intentRsp(intent.getAction(), 0);
        } catch (DbException | NumberFormatException e) {
            e.printStackTrace();
        }
    }

    /**
     * 设备操作成功返回
     * @param intent
     * @param result
     */
    public void intentRsp(String intent, int result) {
        Intent mIntent = new Intent(CommonIntent.ACTION_INFO_RETURN);
        mIntent.putExtra("intentId", intent);
        mIntent.putExtra("return", result);
        mContext.sendBroadcast(mIntent);
    }
}
